Skip to content

fix(studio-server): a file the drive never answers no longer holds a project's first history copy - #8187

Merged
miguel-heygen merged 23 commits into
mainfrom
fix/history-copy-deadline
Nov 21, 2026
Merged

miguel-heygen merged 23 commits into
mainfrom
fix/history-copy-deadline

Conversation

@miguel-heygen

@miguel-heygen miguel-heygen commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

What

A project's first history copy no longer waits forever on a file the drive never answers. Each file it copies gets a deadline (10 s); a file that misses it is left owed, the way a file still changing is, and the background adoption copies it once the drive answers. The open finishes.

Why

On a drive that stops answering (an external exFAT disk was where it showed up), opening a project never finished: the first copy read every file through blobs.put, with no deadline, and the open awaited all of them. The app's main thread stayed free, but the project never opened.

Related work

Refs the desktop app's exFAT project-open freeze: the desktop side moved its own page reads off the main thread with a deadline; this is the part of the open that lives here.

How

  • firstOpen waits on each file's copy for firstCopyFileMs (option, default 10 s). Past it the file reads as "changing", so it joins the owed files that adoptMediaInBackground already retries.
  • The deadline wraps the copy from outside its first-copy slot. A read can't be cancelled, so a stuck read keeps its slot: a dead drive holds the slots the first copy already allows, never more threads than that.
  • storeIfPresent reads one path at a time: a later copy of a path starts after the earlier read ends. A background retry of a stuck file waits behind the stuck read instead of starting a second one on the same drive.
  • A copy that lands after its deadline is kept. Adoption takes those bytes as the file's start, then one more sweep records any edit made since the open as a change. A file whose first try came back missing, still changing or failed is read again from scratch.
  • Late files do not join the adoption chain, so a landed copy is never held behind another file whose read is still stalled. Its hash is kept from pruning until its adoption records it, so a budget prune in between cannot drop the original and make the edited bytes the start.
  • While it waits, that hash counts as baseline in historyBytes() (deduplicated with the tracked hashes), so a waiting copy never pushes an in-budget edit out of undo history. Every fresh read of a file owed from the open, the first and every retry, runs inside the first-copy slots. Every copy the first open or an adoption makes is pinned in the blob store as it is filed (put(path, true)), inside the same per-hash turn a delete takes, so a delete never removes a pinned or newly filed copy; pinned blobs count as baseline in historyBytes(). Only the copy whose put took the pin can release it: the open once the copy is tracked, an adoption after its record. A copy carries whether it is reference-only (a file over 64 MiB or media), so recordAdopted never mistakes one for a lost blob, and it never reads inside the history queue.

An agent step while a first copy is still missing (after merging main)

Main's #8375 makes an agent step wait for every first copy still being taken, so undo can bring back a file the step replaces. Merged with this PR, a file the drive never answers is one of those copies, so the project opened but its first agent step never began.

Decision (the team lead's call, recorded for Miguel): A was "the step waits for the copy, however long". B was "the step waits up to the same 10 s, then begins; undo of that one file refuses rather than restoring the agent's bytes". The lead chose B: a step that hangs forever is not an option, and the refusal uses the words that already exist ("An earlier version of X is not kept"), no new ones.

  • The wait is per file, from when its read starts. Big media files are copied one after another, so a single 10 s budget for the whole step would let a step start on a healthy but slow disk and lose fix(studio-server): an agent step waits for history's first copies, so undo brings old files back #8375's protection. A file queued behind a read that missed its deadline gives up at once, so a dead drive holds a step for about 10 s, not 10 s per file. A file that already missed its deadline during the open gets no second wait.
  • The open's first copies get their budget when their read starts. While a copy waits for one of the four read slots, its budget restarts each time another first copy finishes. So reads queued behind healthy progress are not cut short, and a stalled read is owed 10 s after its own start, however many others finish meanwhile.
  • A step lists the files it could not see (wentAheadOf on its entry): those whose first copy was still pending when it began. Nothing is ever added to a closed entry, so a file is in a step's files only if a sweep recorded it while the step was open.
  • Undo of such a step is all or nothing, decided at undo time. While a listed file is still pending it refuses with "The project's starting copy is still being saved; try again in a moment." After that it refuses with "An earlier version of X is not kept". This covers Cmd+Z and every undo mode, open steps included, and nothing changes. A file never leaves a step's list. Neither its size and times nor its bytes can show that no step wrote it: a rewrite within one time step at the same size keeps the stat, and a file written A, B, then A again by two steps ends with its original bytes. Decision (the team lead's call, recorded for Miguel): a step that went ahead of a stalled file never undoes, the safe side, since no edit is overwritten.
  • The start holds a known original only. It is the copy, when its bytes were read before any step went ahead of the file (the blob store reports that moment through put's onRead, so slow filing does not count against it). Otherwise it is a hash no stored version has, including for a file deleted before its copy landed. Restoring that start, or any point before the step, then refuses for that file.
  • Everything from the unrecorded period is one change, owned by no closed step. The landed file is tracked at its start with no trusted stat, so the next sweep records what stands there now the usual way: into a window open at that moment, else "Changed outside the app".
  • Restore waits with the starting-copy words while any file a step went ahead of is still pending.
  • A Studio claim waits at most the same 10 s for a pending path, and a claim that goes ahead lists that path like a step. A claim on pending paths alone is still its own entry, and the parts a claim cuts from an open step each keep the step's list.
  • A step whose only write was the pending file is an entry, so Cmd+Z stops at it and refuses instead of skipping to an earlier step. While such a step is still open, Cmd+Z stops at it the same way.
  • Every earlier point names a pending file a step went ahead of, as a version not kept, from the moment the step goes ahead until its copy lands. A restore to an earlier point then refuses instead of deleting the file, in this app and in older ones.
  • A later Studio save's receipt never sets the start of a file a step went ahead of: that receipt can name the step's bytes as the ones it replaced. A copy read after the step starts as not kept. A copy read before it follows only the receipts heard by the moment of its read: an early save's original stays the start, and a later save, even one writing the same bytes back, cannot change it.
  • After a restart a pending file a step went ahead of is never trusted. The files steps went ahead of, and each open step's list, are kept in went-ahead.json next to adopting.json. So this holds when the process dies before the step closes: the step recovered from its saved window keeps its list, and it is back before the reopen rewrites that file, so a second crash during recovery keeps it too. The reopen rebuilds the whole list in memory and writes it once, so a crash midway never drops the files after the first. A pending file deleted before the restart keeps a not-kept start.
  • Older app versions: each listed file with no recorded change gets a placeholder change in the entry, written once at commit: before and after are the same 64-hex hash, which no stored version has (the same shape as a big media file's reference, so the log reader keeps it, blobPath accepts it and pruning sizes it at 0). An older app ignores wentAheadOf but sees the placeholder: its plain undo reports a conflict and its back-to-before restore hits "not kept", so neither undoes part of a step. Accepted (the team lead's call, recorded for Miguel): an older app's "Keep later edits" counts the pending file as changed later and undoes the step's other files. It only gets there after its conflict dialog shows that file as changed and the person picks that option. Nothing is overwritten, and that undo can itself be undone.
  • Cost: a step that began while a file's read was stalled never undoes, even if it never touched that file. That is safe but over-refuses, and only after a read stalled past the 10 s deadline.

Package size budget

The required Build job's packed-size check failed: @hyperframes/studio-server packed to 191,358 bytes against a 188,871 budget. Main alone packs to 190,094 (already 0.65% over, inside the check's 1% grace); this branch adds 1,264 bytes of its own history code (826 for the open's deadline, 139 for the step's wait, 299 for the not-kept start). No new import came in: dist/index.js is byte-identical to main's. Following the budget file's rule (5% above measured, as #8176 did for aws-lambda), the budget is now ceil(191,358 x 1.05) = 200,926.

The unpacked check then failed the same way: this head unpacks to 742,597 bytes against main's 732,018 budget (1.4% over, past the 1% grace). The growth is the same history code, unminified in dist: the step's list, its placeholder and the went-ahead file. The unpacked budget is now ceil(742,597 x 1.05) = 779,727. Packed is 192,682, inside the 200,926 budget.

Test plan

  • Unit tests added/updated
  • New firstCopy.test.ts case: one file's open never answers; the history must open, read that file once, and list it in adopting.json. Fails without the fix: run alone against main's projectHistory.ts, the open never resolves and the test times out at 20 s; with the fix it passes in about 140 ms.
  • New firstCopy.test.ts case: the first copy's blob write is held past the deadline, the file is edited after the open, then the write is let go. The original bytes must be the file's start and the edit a change. Fails against the previous head of this branch (START was the edited bytes).
  • New firstCopy.test.ts case: one file's read stalls for the whole test while a second file's first copy lands late, the second file is edited, a sweep with a 1-byte budget prunes, and a claim asks for the second file. Its original bytes must be its start. It fails with either part undone: chained behind the stalled file (never adopted) or not kept from pruning (re-read as the edited bytes).
  • New firstCopy.test.ts cases: a 768-byte late copy waiting to be adopted while a small index.html edit commits under a 128-byte budget (the edit must stay in history), and 12 files whose first copies keep changing (their fresh reads must run 4 at a time). Each fails with its part undone.
  • New firstCopy.test.ts cases: rereads after a first reread also came back changing stay 4 at a time, and a reread copy waiting behind a held sweep survives a 1-byte-budget prune and becomes the file's start.
  • New cases: a file that grew past 64 MiB before its reread is adopted by reference (firstCopy.test.ts), and a pinned blob survives prunes until each pin is released, whether it was new or already stored (blobStore.test.ts).
  • After merging main, new firstCopy.test.ts cases (each failed before its fix, see below):
    • one file's read never answers: an agent step begins within 1.8 s of the open's start at a 1 s deadline (hung before the step's wait; about 2 s with a second deadline);
    • six big files queued behind a read that never answers: the step begins within 1.5 s at a 500 ms deadline;
    • three big files each taking 300 ms under a 600 ms deadline: the step still waits until all three are the start;
    • nine small files reading 120 ms each through four slots under a 200 ms budget: all ten files are the start (before: four);
    • a stalled read next to a read that finishes at 800 ms, at a 1 s budget: the open ends within 1.5 s (a budget stretched by others' progress took 1.8 s).
  • New stepAheadOfCopy.test.ts, one case per row of the table posted on this PR (each failed at 33eafbf1 unless noted):
    • undo while the copy is pending refuses with the starting-copy words, as do restoring the start and the step's own point; both files stay as the agent left them;
    • the copy lands showing the file changed: undo refuses in every mode, restoring the start refuses, nothing changes (already refused at 33eafbf1, kept as a guard);
    • two steps write the file B, then its original bytes, and a third step leaves it alone: undo of each refuses and nothing changes (failed at a2032baa, where matching bytes cleared every list);
    • the step rewrote the file in the same time step at the same size, and the drive reports the stat listed at the open: undo refuses (failed at dfe957d2, where clearing compared stats);
    • a step whose only write was the pending file: Cmd+Z refuses at it, and the cursor and the list are unchanged; the same while that step is still open (failed at a30cf5b0);
    • a person's claim edits an earlier version and the process dies after a later step went ahead of the file; with the lists and adopting.json removed (an app that ignores them), back-to-before of the step refuses and the file stays (failed at a30cf5b0, where the earlier point did not name the file and the restore deleted it);
    • the process dies while the step is open and the step is recovered from its saved window: its undo refuses (failed at a30cf5b0); the same when a second crash hits the first recovery sweep, with the cursor and list unchanged (failed at b910bd69);
    • a Studio save after the agent's write reports the agent's bytes as replaced: for a copy read after the step, the start is not the agent's bytes and restoring it refuses (failed at a30cf5b0); for a copy read before the step, the start is the original, also when Studio saves the original bytes back (failed at b910bd69, where the receipt made the agent's bytes the start); a Studio save heard before the first read keeps its original as the start (failed at 021580df);
    • two pending files and a crash at the reopen's first write of went-ahead.json: both stay listed and neither starts as the agent's bytes (failed at 021580df);
    • wentAheadOf stripped from the log on disk, then reopened (an older app): plain undo and back-to-before are not ok and both files are unchanged; "Keep later edits" undoes the other file and leaves the pending one (the accepted case above);
    • a Studio claim cuts an open step in two: undo of each part refuses;
    • the original was read before the step but filed after it: the original is the start, undo refuses, restoring the start brings every file back;
    • the first reads kept changing until the step rewrote the file: the start is not the agent's bytes and both undo and restoring the start refuse (guard);
    • the step deleted the pending file: undo and restoring the start refuse, nothing changes;
    • a second step began and closed while the file was pending: undo of the first refuses;
    • a person's Studio save of the pending file after the step closed (a write that reports the bytes it replaced): undo of the step never changes that file, and the step's entry names only the file it wrote (at 33eafbf1 undo put the old bytes back over the person's edit);
    • a Studio claim on the pending file answers within 3 s at a 100 ms deadline (hung until the read answered), and its own entry's undo refuses;
    • the process is killed (__fixtures__/stepThenDie.ts) after the step closes, before it closes, or after the step deleted the pending file, and the copy lands after the reopen: the start is not the agent's bytes, restoring the start refuses, and so does undoing the step (the last two failed at dfe957d2).
  • projectHistory.saving.test.ts: a claim on a file still changing after its one retry used to return nothing; it now returns its own entry, whose undo refuses with the starting-copy words and leaves the file as it is. The start now names that file as a version not kept, where before it did not name it.
  • Each part was checked by breaking it, and each break turned its own case red: no undo check, an unbounded claim wait, a queued budget stretched by others' progress, restore checking only the start, no not-kept start for a deleted file, no placeholder, no entry for a pending-only claim, no went-ahead.json, trusting a listed file on reopen, no not-kept start for a file deleted before a restart, a cut part without the list, Cmd+Z ignoring an open step's list, Cmd+Z not refusing before it undoes, a receipt setting an unknown start, no earlier point naming the file, a recovered step without its list, open steps' lists not saved. With all restored, the step, first-copy and saving files passed 46 three times, and the whole studio-server suite passed 2,309 with 0 failures on this head's code.
  • videoState.test.ts: a fixed 80 ms sleep before reading the pending flag became a wait for the flag; it failed once in a loaded full run.
  • Manual testing performed
  • Comments follow CONTRIBUTING.md "Comments"

Limit: this bounds the open and agent steps, not the whole history lifecycle. A read that never answers keeps that file's adoption pending, and closing a history waits for adoption, so a close can still wait on a dead drive.

Not exercised: a real exFAT volume that stops answering; the existing first-copy suite and CI run the rest.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Edit accuracy: accurate 271 (base branch 271), smooth 57 of those

The gate passes.
Smoothness is reported in the artifact, not gated. A case fails only if it fails 2 of 3 runs.

Quarantined, measured but not gated (0)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 29ee475f42ea4e6fd0c74f25c8f6e8223953c7cf.

The deadline correctly sits outside the first-copy limiter, so timing out does not release the underlying read's slot. Per-path serialization also avoids overlapping retries of that read.

Important — retain a successful initial copy that finishes after the deadline (packages/studio-server/src/history/projectHistory.ts:661–664,862–866). owedAfter discards the original promise's eventual result. Adoption waits behind it, then rereads the file and installs those newer bytes as the baseline. If an external editor changes the file after the project opens but before the original blob write finishes, a valid original copy is kept on disk but never referenced by history; the newer content becomes START instead of an undoable change.

Independent reproduction: delay the first incoming-* blob write after the original bytes were read; open with a 50 ms first-copy deadline; externally overwrite the source after open returns; release the original write and wait for adoption to finish. START is the newer digest (f1d822…), not the successfully captured original (f02580…). The added probe fails at this head. The base awaited and used that initial result rather than discarding it.

Carry the late successful result into deferred adoption as the initial baseline, then perform a fresh observation to record changes since it. Do not mark old bytes as the current file version without checking again. Only retry from scratch when the first attempt was missing/changing/failed. Add this delayed-write plus external-edit regression alongside the stalled-open case.

Validation: full build passed; gated firstCopy/projectHistory suites 152 passed, 2 skipped. The named stuck-read regression times out at 20 s with main's production file restored and passes in 134 ms after restoring the fix. The independent late-copy regression fails as described; no real stalled filesystem was used.

Follow-up limit: an actually unending read also keeps its adoption pending, and current close waits for adoption. This fix bounds initial open, not the entire history lifecycle; avoid claiming general stalled-drive recovery.

Need: yes · Size: ok · Reuse: existing first-copy limiter and adoption machinery · Simpler: hand the late copy outcome to adoption rather than losing it · Structure: fine (checked blobStore and recordAdopted; no second history implementation needed)
Risk: medium — changes when the initial undo baseline becomes available.

Verdict: REQUEST CHANGES
Reasoning: Opening now completes, but a successful late original copy can be discarded and an external edit absorbed into the baseline. Preserve that history boundary before approval.

— cutroom-review

@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

Fixed at e718969: a first copy that lands past its deadline is no longer thrown away.

  • firstOpen keeps each owed file's own copy promise and hands it to adoptMediaInBackground. That file's first adoption try awaits it: a stored copy becomes the file's start, recorded against the stat from the open. Only a first try that came back missing, still changing or failed reads the file again from scratch.
  • Once a copy from the open is recorded, the adoption schedules one sweep (sweepIn(0)). The sweeps since open passed this file by while it was adopting, so that sweep reads it fresh and records any edit since as a change. Old bytes are never taken as the current version without that second look.
  • New firstCopy.test.ts case, as you described it: hold the first incoming-* blob write of the original bytes, open with a 50 ms deadline, overwrite the file after open returns, let the write go. START must be the original digest and the edit must be in list(). It fails with this branch's previous projectHistory.ts (START is the edited digest) and passes on the new head: the firstCopy and projectHistory suites, 153 passed and 2 skipped, 3 runs in a row.

On the limit: agreed, and the PR body now says it. This bounds the open only. A read that never answers keeps that file's adoption pending, and close waits for adoption.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — A successful late copy can still be lost while adoption waits. At packages/studio-server/src/history/projectHistory.ts:693, each file’s adoption waits for the previous file’s first try. When two files miss the deadline, the first file can remain stalled after the second file has successfully copied. A claim for the second file then waits behind the unrelated read. Its completed blob is also absent from the prune keep-set at line 1159. In an isolated test, I edited the second file after open, triggered budget pruning with unrelated writes, then released the first read. The second file’s original blob had been pruned, and recordAdopted used the edited bytes as START.

Make completed late copies available for adoption independently of stalled paths and keep their blobs through the baseline commit. Please exercise a claim and pruning while an earlier file remains stalled, while preserving the first-copy slot limit.

Full build and studio-server typecheck passed. The history suite reported 317 passed and 2 skipped. Both named regressions passed at this head and failed against their respective earlier versions. The stalls were simulated with local fixtures. No failing-drive hardware was exercised. CI was still running at review time.

— tai (automated review)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at e718969d9868acdc63432288e4170377b1d23e54, delta from 29ee475f42ea4e6fd0c74f25c8f6e8223953c7cf.

The original single-file late-copy case is repaired: the successful first result is handed to adoption, then a fresh sweep records the intervening edit.

Important — the same baseline loss remains when another file stalls first. +1 to the existing review. I independently traced the same case before reading that review: projectHistory.ts:693 (adoptMediaInBackground) serializes each first adoption behind the previous one, while projectHistory.ts:1159 (keepWithinBudget) does not retain a completed-but-unadopted first-copy hash. projectHistory.ts:776 (recordAdopted) then rereads the edited source if that blob was pruned, making the newer content START again.

Keep completed first-copy hashes referenced through their baseline commit, and allow their adoption without waiting on an unrelated stalled path; retain the existing copy-slot limit. Add the two-file scenario with both an unrelated budget-pruning commit and a claim for the completed file while the earlier read remains held. This is a remaining case of the previous baseline blocker, now also demonstrated by Tai, rather than a request to solve all stalled-drive behavior.

Validation: full bun run build passed. Gated firstCopy.test.ts and projectHistory.test.ts: 153 passed, 2 skipped, plus my independent two-file pruning probe failed. It held both original blob writes beyond the deadline, released B while A stayed held, edited B, and flushed an unrelated file with a zero history budget. The probe first confirmed B’s original blob had actually been pruned; after releasing A, START contained the edited digest (139249…) rather than the original (c3ca705…). The same probe with a larger budget retains the blob and passes (1 passed), isolating pruning as the cause. The submitted single-file delayed-write regression passed; restoring only projectHistory.ts from 29ee475f makes it fail, and restoring this head gives 1 passed. A fresh adversarial source pass independently checked the newly exposed prune window against the base.

The description correctly limits this to initial open: a permanently stalled read can still hold close. No real failing exFAT drive was exercised.

Need: yes · Size: ok · Reuse: existing first-copy limiter, adoption and blob keep-set · Simpler: retain and adopt completed outcomes directly · Structure: fine (checked blobStore, recordAdopted and keepWithinBudget; no parallel history implementation needed)
Risk: medium — successful initial bytes can still be lost from the undo baseline.

Verdict: REQUEST CHANGES
Reasoning: The single-file repair works, but a completed late copy can still be pruned while an unrelated adoption holds it back.

— hf-review

@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

Fixed at 4892c12, for both reviews (the two-file case).

  • Adoption no longer waits on an unrelated stalled path. adoptMediaInBackground chains only the files it reads itself. A file owed from the open already has its own copy in flight inside the first-copy slot limiter, so it is not part of the chain, and nothing after it waits on it. The first-copy slot limit is unchanged.
  • A landed late copy is kept through the baseline commit. When an owed file's first copy lands, its hash goes into lateFirstCopiesKeptFromPruning, which keepWithinBudget adds to the prune keep-set. It leaves that set once the file's first adoption try ends. So recordAdopted finds the original blob and never re-reads the edited source for START.
  • New firstCopy.test.ts case, as you both described it: p0's read stays held for the whole test. p2's first copy is held past the deadline. A checkpoint sweep of an edited index.html holds the history queue. Then p2 is edited, its original write is released, and a claim is made for parts/p2.js. The sweep's record runs with a 1-byte budget, so it prunes. START for p2 must be the original digest, read before the sweep that records the edit (the 1-byte budget would fold that edit into START), and the claim must resolve while p0 is still held.
  • Checked on Linux, 3 runs in a row: firstCopy and projectHistory suites, 154 passed, 2 skipped. Broken once each: chaining late files again fails the new case (p2 is never adopted while p0 is held), and dropping the keep-set entry fails it (p2 re-reads as the edited bytes). The comment ratchet passes.

The limit in the body stands: a read that never answers still keeps that file's own adoption, and close, waiting.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new two-file regression passes, and an independent claim test confirms that a completed late copy can be adopted while a different read remains stalled. Two regressions remain.

  • P1 — A pending baseline copy can evict unrelated undo history. In packages/studio-server/src/history/projectHistory.ts:1157, historyBytes() subtracts tracked hashes only. A late first copy is now protected from pruning but still counts toward the budget until adoption gets its turn on the history queue. In a gated test, a 768-byte pending file caused a small, otherwise in-budget index.html edit to be folded into START. After the file was adopted, the edit was still missing from history. The same edit survives when that file finishes during open. Exclude protected baseline hashes from the budget while they await adoption, deduplicating them with the tracked hashes.
  • P2 — Changed or failed first copies can fan out into parallel retries. At packages/studio-server/src/history/projectHistory.ts:699, having a first-copy promise bypasses the serial adoption chain even when that promise produces no usable copy. The fallback at line 765 then reads outside the first-copy slots. A fixture where 12 files each reported changing before the deadline reached 12 simultaneous fallback reads. The previous head stayed within four in the same fixture. Let successful copies reach the history queue independently and bound the fresh reads that follow an unsuccessful copy.

The history suite passed 318 tests with two skips. The new regression and the two review cases used controlled I/O. No physical drive was tested.

— tai (automated review)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 4892c12fcf69ee3d99d2c742d10502f0bdea2c19.

The previous two-file late-copy/prune/claim scenario is fixed. I independently reproduced both new cases in tai's review:

  1. Important — protected baseline bytes consume the undo budget before adoption. projectHistory.ts:1157 subtracts tracked hashes only. A protected 768-byte late copy awaiting the history queue still consumes a 128-byte history budget, so committing a small index edit folds that otherwise retainable edit into START. The history list becomes empty. Exclude protected baseline hashes from historyBytes(), deduplicated with tracked hashes. This loses the undo step, not the current file contents.
  2. Important — unsuccessful first copies bypass the read limit. At :699 and the fallback at :765, merely having a first-copy promise bypasses the serial chain even when it returns changing. Twelve such files start twelve simultaneous fresh fallback reads. Keep successful copies independently adoptable, but send fresh fallback reads through the existing shared first-copy limiter.

Validation: full build passed. Focused firstCopy/projectHistory suites passed 154 existing tests with two skipped, plus an independent successful-stall slot probe. Three additional probes pass one and fail two on this head; all three pass with prior e718969d source. A temporary deduplicated budget exclusion and bounded-fallback correction passes all nine firstCopy/probe cases. The submitted two-file regression fails with prior/no-pin controls and passes after restoration. Temporary changes restored.

The successful-stall slot test does not cover the unsuccessful-copy fallback; no physical failing-drive behavior was exercised.

Need: yes · Size: ok · Reuse: existing first-copy limiter and history budget accounting · Simpler: count pending baseline bytes as baseline and limit fresh reads · Structure: fine (checked adoption, pruning and copy lifetime; no new subsystem)
Risk: medium — undo steps can be folded early and fallback reads exceed their intended bound.

Verdict: REQUEST CHANGES
Reasoning: The earlier baseline-loss case is repaired, but the new pin and independent-adoption paths need consistent budget and concurrency accounting.

— Rames (hf-review)

@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

Fixed at 68a04bb, for both reviews.

  • Waiting baseline bytes no longer use the undo budget. historyBytes() subtracts the hashes in baselineAwaitingAdoption together with the tracked hashes, deduplicated in one set. A landed late copy counts as baseline from the moment it lands, so an in-budget edit committed while it waits for the history queue is no longer folded into START.

  • Unsuccessful first copies read inside the first-copy slots. Successful late copies stay independently adoptable. The fresh read that follows a late first copy that came back changing, gone or failed now runs through inFirstCopySlot, so those reads are bounded by the same four slots as the first copy.

  • New firstCopy.test.ts cases:

    • Budget: a 768-byte parts/p1.js copy lands late and waits behind a held sweep, while a small index.html edit commits under budgetBytes: 128. Once p1 is adopted, list() must still have the index.html change.
    • Fan-out: 12 files whose every first-copy read sees the file change under it. Their fresh reads must reach 4 at once and never more.
  • Checked on Linux, 3 runs in a row: the firstCopy and projectHistory suites, 156 passed, 2 skipped. Broken once each, every part fails its test:

    • Late files chained again: p2 is never adopted while p0 is held.
    • Keep-set entry dropped: p2 is re-read as the edited bytes.
    • Budget exclusion dropped: expected [] to include 'index.html'.
    • Fallback outside the slots: expected 12 to be 4.

    The comment ratchet passes.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The undo-budget regression and the first fallback read limit now pass. Two remaining cases reproduce with controlled I/O.

  • P1 — Pruning a completed fallback can put a stalled read back on the history queue. In packages/studio-server/src/history/projectHistory.ts:765, a fresh fallback result queues adoption without protecting its hash. The initial late-copy path protects its hash while waiting, but the fallback does not. I held a checkpoint while one fallback stored its bytes, edited that file, then let the checkpoint prune. The fallback blob was removed. recordAdopted then started a third read inside the history queue at line 784. While that read was stalled, a claim on a different, successfully copied path stayed pending. After release, the edited bytes became START. Keep successful fallback copies through queued adoption, and keep any necessary fresh read outside the history queue.
  • P2 — The second fallback bypasses the four-slot limit. At packages/studio-server/src/history/projectHistory.ts:765, slot use depends on late. The adoption loop clears it after its first try, then retries independently. In a 12-file test where both initial and first fallback copies reported changing, the next retry started all 12 reads together. Preserve whether the adoption came from first open across retries and apply the same slot bound to each fresh read.

The new concurrency test also matches a hard-coded /parts/ substring at packages/studio-server/src/history/firstCopy.test.ts:350, which misses native Windows paths. Match the platform-native fixture directory and release the read gate in a finally so a failed assertion can finish teardown.

The history suite passed 320 tests with two skips. Studio Server typecheck passed. The Windows path concern was checked with path semantics. No physical drive or Windows test run was used.

— tai (automated review)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 68a04bbce32ef765946e2958e2f7f93212255624, delta from 4892c12f.

The two prior introduced regressions are fixed: protected pending-baseline hashes are deduplicated with tracked hashes before budget accounting, and the first fresh fallback uses the existing read-slot limiter. The earlier late-copy adoption and two-file pruning fixes remain covered.

Pre-existing follow-ups: I independently reproduced both cases in tai's latest review: pruning a completed fresh fallback can trigger a reread inside the history queue, block an unrelated claim and change START; a second fallback can reach twelve simultaneous reads. Crucially, the identical probes produce the same failures on this head, 4892c12f, e718969d, and pre-PR parent 959edbcd0737b7953ba2d9976b413a48312b4adf. Those returned-changing-copy cases predate this PR, so they do not block this improvement. Follow up by protecting every successful fallback hash until adoption, keeping necessary rereads outside the history queue, and preserving the limiter across every retry.

Nit: as tai noted, use the platform-native fixture path instead of /parts/ in the new test, and release held read gates in finally blocks.

Validation through the shared test gate: firstCopy/projectHistory suites at this head 159 passed, 2 skipped; the two previous-regression probes fail against 4892c12f, and the restored focused run passes 11 tests. The two additional follow-up probes fail identically at all four refs above. Temporary source substitutions were restored. No physical stalled-drive or Windows run was performed. This approves the initial-open improvement, not a claim that every history lifecycle operation is bounded.

Need: yes · Size: focused re-review · Reuse: existing baseline protection, budget accounting and first-copy limiter · Simpler: retain those mechanisms · Structure: fine (checked adoption, claim queue and blob pruning; no parallel subsystem)
Risk: medium — changes the timing of persistent undo baselines.

Verdict: APPROVE.
Reasoning: the regressions introduced by the prior revision are repaired; independently verified base behavior remains documented for follow-up.

— Rames (hf-review)

@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

Fixed at 4b65fe7. Rather than closing one more path, this puts the three rules every adoption read follows in one place, in tryAdopting and recordAdopted:

  • Every fresh read of a file owed from the open runs inside the first-copy slots, on every try. adopt captures owedFromOpen once and passes it to every tryAdopting call, so the retry after a fallback that came back changing takes a slot too. Files that were never owed (large media, adopted in the background chain) read as before.

  • Any copy an adoption holds is kept until it is recorded. tryAdopting puts the hash of whatever copy it is about to record, from the open or from a fresh read, into baselineAwaitingAdoption before queuing. That set is both in the prune keep-set and counted as baseline in historyBytes(). It is cleared after the try.

  • No read happens inside the history queue. When the blob is gone, recordAdopted now returns changing instead of calling storeIfPresent inside the queue, and the adoption's retry reads again outside it. With no read inside the queue, a stalled read can no longer hold it or a claim on another path (traced in the code; the claim case is not a test here).

  • Test fixes from your notes: the fan-out test matches join(projectDir, "parts") + sep, not /parts/, and releases its gate in finally.

  • New cases: the fan-out test also runs with six changing reads per file, so the retry after the first fallback must stay at 4 at once. A reread copy is held behind a sweep, the file is edited, and a 1-byte-budget prune runs; START must still be the reread bytes.

  • Checked on Linux, 3 runs in a row: firstCopy and projectHistory, 158 passed, 2 skipped. Broken once each, every rule fails its own test:

    • Late files chained.
    • Late copy not kept.
    • Waiting copy counted as history.
    • Fresh reads outside the slots: 12, not 4.
    • Only the first reread in a slot: 12, not 4.
    • Reread copy not kept: p1 never becomes START.

    The comment ratchet passes.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested at 4b65fe7cc5b876de7aacc75f7e9b603c3a04fb02

  • P1 · Protect reread bytes when the blob is published. In packages/studio-server/src/history/projectHistory.ts:768, adoption marks the hash after the copy promise resolves. The blob store can already list the new hash by then. A checkpoint can capture its keep set in that gap and prune the fallback copy. A controlled local I/O probe confirmed the original blob disappeared and a later edit became START. Hold the blob as part of publishing it, and keep that protection through the baseline commit. The new retry correctly runs outside the queue, so an unrelated checkpoint can still finish while the retry waits.
  • P2 · Carry the copy policy of the bytes actually read. In packages/studio-server/src/history/projectHistory.ts:787, the missing-blob check uses the size captured at the initial scan. When an owed file starts below the threshold but grows past 64 MiB before its fallback read, storeNow returns a valid reference-only hash. Adoption treats it as a lost blob and rehashes it on every retry without adding it to START. The same sparse-file test adopted it on 68a04bbc and failed on this head. A local control carrying the reference-only result from storeNow passed.

The later retries stayed within four slots, and the portability change uses the native path separator. All 322 focused history tests passed with two skips. Studio Server typecheck passed. The timing probes used local temporary files and controlled I/O.

— tai (automated review)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 4b65fe7cc5b876de7aacc75f7e9b603c3a04fb02.

The previous completed-fallback and second-retry probes now pass: the copy is retained through queued adoption in those scenarios, and later retries use the four-slot limiter. The native-path/finally test changes are also present.

Important — carry the policy of the copy actually read. +1 to tai's second finding, independently reproduced. At packages/studio-server/src/history/projectHistory.ts:787, recordAdopted checks isUncopied using the size from the initial directory listing. An owed non-media file can grow beyond 64 MiB before its fallback read. storeNow correctly returns a reference-only hash using its current stat, but no blob exists for that policy. Adoption uses the old small size, treats the valid reference as missing, returns changing and repeats instead of entering START.

An independent sparse 65 MiB fixture remains unadopted through the bounded retry observation at this head; the identical growth case passes at 68a04bbc. The source predicate explains why further retries keep making the same decision. Carry the copy/reference-only decision alongside the hash in Copied, and consume that decision in recordAdopted rather than restatting or using old ListedFile metadata. A temporary implementation of that correction passes all three targeted probes.

Validation via the test gate: 160 focused tests passed, 2 skipped, with the additional growth probe failing. Against 68a04bb, the two previous fallback/retry probes fail while the growth case passes. Temporary correction: 3/3 passed; restored current-source rerun of the two previous cases: 2/2 passed. Source restored clean. This uses controlled local I/O and a sparse file, not a real failed drive or a performance benchmark.

Tai also reports a narrower publication/pruning window. I have not independently reproduced that exact timing window and make no additional verification claim about it here.

Need: yes · Size: focused re-review · Reuse: existing isUncopied policy, carried with its result · Simpler: avoid deciding copy policy twice from different metadata · Structure: fine (checked storeNow → recordAdopted; no new subsystem)
Risk: medium — an owed file can retry without becoming an initial history entry.

Verdict: REQUEST_CHANGES.
Reasoning: the new missing-blob retry must distinguish a deliberately reference-only result from a lost copied blob.

— Rames (hf-review)

@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

Fixed at 065757f, for both reviews.

  • The copy is protected as it is published. BlobStore.put(path, pin) pins the blob in the same synchronous step that files it, both for new bytes and for bytes the store already held. prune skips pinned blobs. A put waits for any in-flight forget of the same hash before it checks the store, so it can never pin a blob that is being deleted. The first open's copies and every adoption read are pinned puts. The open unpins a copy once it is tracked, and an adoption unpins its copy after its record has been written, so the protection lasts through the baseline commit with no gap. Pinned blobs count as baseline in historyBytes(), which replaces the separate baselineAwaitingAdoption map.
  • The copy policy travels with the bytes read. storeNow returns { hash, referenced: true } for a file hashed in place (over 64 MiB, or media), and recordAdopted checks that flag instead of the size from the open scan. An owed file that grew past 64 MiB before its reread is now adopted by reference.
  • New tests:
    • firstCopy.test.ts: a file whose third first-copy read sees it grow to a 65 MiB sparse file must reach START.
    • blobStore.test.ts: a pinned new blob and a pinned already-stored blob survive prune(new Set()) until every pin is released.
  • Checked on Linux, 3 runs in a row: firstCopy, projectHistory and blobStore, 175 passed, 2 skipped. The studio-server typecheck is clean for src/history. Broken once each, every rule fails its own test:
    • Late files chained behind a stalled one.
    • First copies not pinned.
    • Pinned copies counted as history.
    • Rereads outside the slots: 12, not 4.
    • Only the first reread in a slot: 12, not 4.
    • Adoption rereads not pinned.
    • A reference-only copy read as a lost blob.
    • Prune ignores pins: both blob store cases.
  • The microsecond window between publish and protection that tai found is closed by construction (the pin is taken where the blob is filed). It isn't reproduced with a timing test.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested at 065757f6

  • [P1] Serialize publication against pruning for the same hash. In packages/studio-server/src/history/blobStore.ts:233, the write checks for an in-flight deletion before it stages the bytes. A prune can start against an earlier copy of the same hash during staging. In a history fixture, the fallback wrote and pinned the original bytes while the earlier deletion was in progress. The deletion removed the new copy, and adoption recorded the edited bytes as START. Keep deletion and publication for a hash mutually exclusive through the final rename and registration.
  • [P1] Release only pins a copy acquired. In packages/studio-server/src/history/projectHistory.ts:675 and :775, reference-only results call unpin even though they did not pin anything. With an MP4 and a JS file containing identical bytes, recording the MP4 reference released the pending JS pin. After the MP4 was removed, pruning dropped the pending copy and adoption used the edited bytes as START. Carry pin ownership with the copy result and release only the acquired pin.
  • [P2] Release the deduplication pin if staging cleanup fails. In packages/studio-server/src/history/blobStore.ts:272, a simulated EPERM while removing the duplicate staging file rejected put and left the pin behind. A subsequent prune retained the blob for the store's lifetime. Release the pin on rejection.

The previous fallback-publication probe passed, and the 65 MiB growth probe verified that START holds the correct reference hash without storing a blob. 325 focused history tests passed with two skips, and the Studio Server typecheck passed. The new failures were reproduced with local files and controlled filesystem timing or errors. A real stalled drive and the full monorepo suite were outside this local run.

— tai (automated review)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 065757f6b2520f192729544510337e5ceeef63ae.

The prior reference-only growth and retry cases now pass. I independently reproduced the three pin-ownership problems in tai's current review:

  1. Important — publication and deletion of the same hash still overlap. At blobStore.ts:233,268, awaiting forgetting.get(hash) does not protect the later publication. My actual-store probe exercises the narrower check/await interleaving: no deletion is recorded at the check, pruning starts during the await, put returns the existing hash with a pin, then the held deletion removes that still-pinned blob. Coordinate publication/pin acquisition and deletion per hash through the final operation; a one-time pre-check is insufficient. This probe establishes that overlap, not every staging interleaving in tai's report.
  2. Important — reference-only results release another copy's pin. At projectHistory.ts:675,775, unpin runs for a reference-only result that acquired no pin. An actual history fixture with identical MP4/JS bytes releases the pending JS pin when the MP4 is recorded. Removing the MP4, pruning and editing the JS then installs edited bytes as START. Carry pin ownership with the result and release only the ownership that operation acquired.
  3. Important — failed duplicate staging cleanup leaks its acquired pin. At blobStore.ts:270-273, pinning precedes awaited temporary-file removal. A controlled EPERM makes put reject without returning ownership to its caller, leaving the blob protected from pruning for the store's lifetime unless another operation releases it. Release the acquired pin on rejection, or transfer ownership only after cleanup succeeds.

Validation through the shared gate: 178 checks passed, 2 skipped, with three new probes failing. Temporary diagnostic corrections pass all six targeted probes; the conditional-await diagnostic only counterchecks the observed overlap and is not proof of a complete publication/deletion design. Source restored; the three prior regressions pass again. Tests use local files and controlled filesystem timing/errors, not a real stalled drive.

Need: yes · Size: focused re-review · Reuse: existing blob-store copy policy and adoption handoff · Simpler: explicit owned-pin release and per-hash coordination · Structure: fine (checked store publication, pruning and both engine release sites; no second history subsystem)
Risk: medium — a supposedly retained baseline can be deleted, or a failed copy can retain storage indefinitely.

Verdict: REQUEST_CHANGES.
Reasoning: the new pin must have one owner and remain effective across deletion, reference-only results and cleanup errors.

— Rames (hf-review)

@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

Fixed at 59d9710, for both reviews.

  • Publication and deletion of a hash are mutually exclusive. The blob store gives each hash one turn at a time (inTurn). forget runs its delete inside the hash's turn, and it skips the hash if a pin was taken while it waited. Publication runs its whole store step inside the same turn: the existing-hash check, the final rename, the registration and the pin. Only staging the bytes happens outside it. So a delete can never remove a copy filed after it started, and a put can never pin a blob that a delete in progress then removes. The pin check lives in forget alone, so prune and drop share it.
  • A pin is released only by its owner. storeNow gives a copy a release only when its own pinned put took the pin. Reference-only copies (media, files over 64 MiB) and unpinned puts carry none. The open and the adoption call copied.release?.(), so an MP4 reference can no longer release a JS file's pending pin on the same bytes.
  • A failed staging cleanup leaves no pin. In the duplicate path, the staged file is removed before the pin is taken, so an EPERM on that removal rejects the put with nothing pinned.
  • New blobStore.test.ts cases:
    • A prune is held mid-delete. A pinned put of the same bytes reads them and reaches the store, then the delete finishes. The blob must exist with the original bytes.
    • An EPERM on removing a staged duplicate rejects the put and leaves pinned() empty.
  • Checked on Linux, 3 runs in a row: firstCopy, projectHistory and blobStore, 177 passed, 2 skipped. The studio-server typecheck is clean for src/history, and the comment ratchet passes. Broken once each, every rule fails its own test:
    • Late files chained.
    • First copies not pinned.
    • Pinned copies counted as history.
    • Rereads outside the slots, and only the first reread in a slot: 12, not 4.
    • Adoption rereads not pinned.
    • A reference-only copy read as a lost blob.
    • A delete ignoring pins.
    • Publish and delete not taken in turn.
    • A pin taken before the staged duplicate is removed.
  • Not a dedicated test: pin ownership across an MP4 and a JS file with the same bytes. It holds by construction (a reference-only copy has no release), and isn't replayed as your fixture did.

…line

# Conflicts:
#	packages/studio-server/src/history/projectHistory.ts
Main packs to 190,094 bytes, already 0.65% over the 188,871 budget; this branch adds 1,264 bytes of its own code (no new import: dist/index.js is unchanged). The budget file's rule is 5% above measured: ceil(191,358 x 1.05) = 200,926.
… Cmd+Z, restarts, in older apps

Cmd+Z stops at an open step whose only write so far is a pending file. A step recovered after the process died
keeps its list of pending files. A later Studio save's receipt no longer sets the start of a file a step went ahead
of. Every earlier point names a pending file as not kept, so no restore deletes it in any app version.
…does, whatever bytes land

Bytes cannot tell steps apart: a file written A, B, then A again by two steps looked untouched and cleared both. A
step's list of files it went ahead of is now never cleared, so its undo refuses after a stalled read.
@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

At b910bd69, answering the two reviews at a30cf5b0. Each item has a stepAheadOfCopy.test.ts case that fails at the head named in its row and passes now. Each fix was checked by breaking it.

A→B→A (Rames). A step's list is never cleared now. Bytes cannot tell steps apart, and size and times cannot either. Only the CLI's watcher reports writes as they happen, so other hosts have no per-step record of which step wrote a file. A step that went ahead of a stalled file never undoes. That is the safe side, chosen by the team lead and recorded in the body. Clearing is deleted (judge, verdictDue, seenUnchanged), and the case "file changes while its copy is being filed" went with it, since it no longer pins anything. New case: two steps write // B, then // before, and a third step leaves the file alone. Undo of each refuses and nothing changes. It failed at a2032baa.

Tai's four

  • Cmd+Z and an open pending-only window. next() counts an open step's list, and Cmd+Z refuses before it undoes anything. The case keeps the window open. Both files, the list and the cursor stay put.
  • A recovered window. Each open step's list is saved in went-ahead.json, and the window recovered from its saved descriptor gets its list back. Case: the process dies while the step is open, and the recovered step's undo refuses.
  • Receipt start. A copy read after a step went ahead gets a not-kept start, before any receipt is consulted. Case: Studio saves after the agent with a receipt naming the agent's bytes. The start is not those bytes, and restoring it refuses. A copy read before the step keeps the original (guard).
  • Older reader, back-to-before after a crash. From the moment a step goes ahead of a pending file, every earlier point names the file as a version not kept. A restore then refuses before writing anything, in any app version. Case: an earlier claim, a crash after a later step, then the lists and adopting.json removed. Back-to-before of the step refuses, and the file stays.
  • Older reader, "Keep later edits". Kept as it is, by the team lead's call, recorded in the body. That mode only runs after the older app shows the pending file as changed and the person picks it. It leaves that file as the agent left it and undoes the rest. Nothing is overwritten. The older-reader case pins this behaviour.

Non-blocking from Rames: the in-memory verdict and a cleared step left with 0 files are both gone with clearing.

Checks

  • 4 cases failed at a30cf5b0, and the A→B→A case failed at a2032baa.
  • 6 breaks, each red on its own case. They ran on a2032baa; the lines they break are unchanged since.
  • The step, first-copy and saving files passed 46 three times.
  • Whole studio-server suite: 2,305 passed, 0 failed.
  • tsc clean, box pre-commit clean.
  • The push gate ran 2 named files 3 times, plus 25 covering files.

Not exercised: a native Windows run and a real drive that stops answering. These were Linux runs with local fixtures.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two P1s at b910bd69.

  1. Recovery can erase the window’s Undo guard before it commits the recovered entry. packages/studio-server/src/history/projectHistory.ts:707–714,844–881. markWentAheadBeforeReopen rewrites went-ahead.json while this.windows is still empty. If recovery is interrupted before settleAll commits the recovered window, the next launch reads windows: {}. I reproduced this with the existing mid-step crash fixture and a second exit at the first recovery sweep. On the next launch, Undo returned ok: true, restored index.html, and left parts/p1.js at the agent’s bytes. Keep the saved guard until the recovered entry is durable. Add the second-interruption case and assert that both files and the cursor stay unchanged on refusal.

  2. A later save can still replace a known START with the agent’s bytes. packages/studio-server/src/history/projectHistory.ts:1033–1037. The early return fixes the unknown-provenance case. For a read-before copy, START still follows the receipt chain by content hash. Hold filing after the first read takes A, let the agent write B, then let Studio save A with a receipt saying it replaced B. The late copy’s hash A now matches that newer receipt. I changed the new read-before test to use this schedule and confirmed START became B and Restore START overwrote Studio’s A with B. Preserve the known original for read-before copies, or constrain receipt lookup to receipts known to predate the read.

The A→B→A step now refuses Undo permanently as intended. The open pending-only Cmd+Z, one-crash recovery, unknown-copy receipt and older-reader back-to-before cases passed in the focused suite. I treated the explicitly accepted older-reader “Keep later edits” behavior as settled. History and route tests on Linux: 427 passed, 3 skipped. The two additional cases were verified with local fixtures. Native Windows and the remaining hosted checks were pending when checked.

— tai (automated review)

@jrusso1020 jrusso1020 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve at b910bd6. My a30cf5b blocker is resolved, and so are the four other findings.

Need ✅ · Size ✅ (+179/−81 since a30cf5b0, mostly tests) · Reuse ✅ (one went-ahead.json carries pending files and open windows) · Simpler ✅ (the byte-match clearing path is deleted, not patched) · Structure ✅
Risk: low to medium. A step that went ahead of a pending file now refuses its undo for good, even when the bytes return to the original. That trades a rare false refusal for never undoing to a wrong file, which is the right side to err on.

Prior findings, checked at this head

  • A→B→A: judge, seenUnchanged and verdictDue are gone, so no read can clear a step's list. The test "refuses the undo of every step that went ahead, though the file ends with its original bytes" runs exactly that case. All three steps refuse, and both files are left as they were.
  • Cmd+Z on an open window: next() now counts an open window's wentAheadOf as a write, and step calls refuseUnseen before undoing.
  • A window recovered after a crash: went-ahead.json is now { pending, windows }, and reopenClosedWindow restores the window's list. The stepThenDie fixture sends the step id before the SIGKILL. went-ahead.json is not on main, so no older on-disk format needs reading.
  • A receipt never sets an unknown start: adoptedStart returns the not-kept hash for unknown provenance before it consults overwritten.
  • Earlier points name the file: nameAtStart records the file at the start as not kept. When the copy lands, startSeen/startUnseen replace that with the real start, so a known original stays restorable.

What I ran

  • vitest run src/history: 393 passed, 3 skipped (23 files).
  • I put a30cf5b's projectHistory.ts back under this head's tests. Six fail: the A→B→A case, the open-window Cmd+Z, the recovered window, the receipt start, earlier points naming the file, and the saving test's start assertion. Each fix has its own red test.
  • tsc --noEmit on studio-server is clean.

— Rames (hf-review)

… crash; saves keep the start

The closed window is recovered before the reopen rewrites went-ahead.json, so a crash during recovery no longer
erases its list of pending files. A copy read before a step went ahead is the file's start whatever a later save's
receipt says it replaced.
@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

At 021580df, answering the review at b910bd69. Both cases fail at b910bd69 and pass now, and each fix was checked by breaking it.

  • Second crash during recovery. The closed window is recovered before the reopen rewrites went-ahead.json, so the saved list stays until the recovered entry is in the log. The fixture now has a reopen mode that dies at the first recovery sweep, the moment it reads index.html, before anything commits. Case: a crash mid-step, a second crash during recovery, then a third open with the read still stalled and a Studio claim committing the recovered step's writes. Undo of every part refuses, and both files, the cursor and the list stay unchanged. Moving the recovery back after the rewrite turns it red.
  • A save back to the original bytes. A receipt is consulted only for a file no step went ahead of. A copy read before the step is the start, and a copy read after it starts as not kept. Case: filing is held after the first read takes // before, the agent writes // agent, and Studio saves // before with a receipt saying it replaced // agent. The start is // before. At b910bd69 it was the agent's bytes.

Checks

  • The step, first-copy and saving files passed 48 three times.
  • Whole studio-server suite: 2,307 passed, 0 failed.
  • tsc clean.
  • The push gate ran 2 named files 3 times, plus 25 covering files.

Not exercised: a native Windows run and a real drive that stops answering. These were Linux runs with local fixtures.

@terencecho terencecho left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — Restore Start can lose the original from a Studio save that predates the stalled step (packages/studio-server/src/history/projectHistory.ts:1035).

The new read-before branch bypasses every receipt. Reproduced with a file at A and its first read delayed: Studio saves B and records overwrote: A before that read completes. The read gets B, its blob filing stalls, and a Studio claim and an agent window proceed. The agent only edits index.html. After filing completes, Restore Start succeeds and restores the index but leaves B. The same test restores A at b910bd69. The receipt naming A came before the read and the agent window.

Keep the trusted receipt ancestry available when the bytes are read. The existing regression test should continue to reject the receipt from a later save that names the agent's bytes. Add the early-save case alongside it.

P2 — A second crash can still lose part of the pending-file list (packages/studio-server/src/history/projectHistory.ts:852).

The recovered window's undo guard now survives the sidecar rewrite. With two pending files, though, the loop calls markWentAhead and rewrites went-ahead.json after adding the first path. A crash at that write leaves the window's guard intact but drops the second path from pending. In the two-file probe, the next reopen treats the second path as tracked and hangs when its read is stalled. An uninterrupted reopen completes, as does the crash probe with a single write after the full list is rebuilt.

Keep the old sidecar intact until recovery can replace it with the full pending list and recovered window guard.

— tai (automated review)

…pen writes all pending files

A copy read before a step went ahead follows only the save receipts heard by the moment of its read, so an early
save's original stays the start and a later save naming the step's bytes cannot replace it. The reopen rebuilds
the list of pending files in memory and writes it once, so a crash midway keeps every file on it.
@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

At 2e293fc3, answering both findings at 021580df. Both cases fail at 021580df and pass now, and each fix was checked by breaking it.

  • An early save's receipt. At the moment of its read, a copy now keeps a snapshot of the save receipts heard so far. A copy read before a step went ahead follows only that snapshot, so a save heard before the read still names the original, and a save heard after it, the step's bytes included, cannot. Case: Studio saves // saved over // before with its receipt before the stalled first read, the read takes // saved, filing waits, then a step edits only index.html. The start is // before. Breaking it either way turns a case red: following the current receipts reds the later-save case, and following none reds this one.
  • Two pending files and a crash during the reopen's rewrite. The reopen rebuilt went-ahead.json one file at a time. It now rebuilds the list in memory and writes it once (temp file, then rename). Case: two stalled files, a crash after the step, then a crash at the reopen's first write of the list. Both files stay listed, and neither starts as the agent's bytes. Writing file by file again turns it red.

Checks

  • The step, first-copy and saving files passed 50 three times.
  • Whole studio-server suite: 2,309 passed, 0 failed.
  • tsc clean.
  • The push gate ran 2 named files 3 times, plus 25 covering files.

Not exercised: a native Windows run and a real drive that stops answering. These were Linux runs with local fixtures.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested at 2e293fc3. The full pending-set rewrite survives the second crash with both files, and the prior early/late receipt controls pass. Three first-copy boundary cases still fail.

  1. P1 · A late receipt can still change Start when no agent step opened (packages/studio-server/src/history/projectHistory.ts:1050). Hold publication after the first copy reads A. The file changes to B, then Studio saves A with a receipt naming B. The no-step branch walks the live receipts, so History records B at Start. Restore Start then writes B over A. Use read-time receipt ancestry for that adoption path too.
  2. P2 · Delayed close can discard a valid pre-step original (packages/studio-server/src/history/blobStore.ts:263). For a small file, the bytes and their stat are verified before awaiting the source handle's close. Holding that close until a step edits the file makes the later onRead classify the already verified copy as unknown. The original is in the blob store, but Restore Start refuses. Capture the read event at successful byte validation and retain normal close error handling.
  3. P2 · Pruning can discard bytes a pending receipt snapshot still needs (packages/studio-server/src/history/projectHistory.ts:1505). Early save B over A, hold publication of B, then record a later save that disconnects the live receipt chain. The old A blob exists before pruning. A commit that prunes while filing is held deletes A because it is named only by the read-time snapshot. Restore Start then succeeds with B. The same sequence preserves A without pruning. Keep the needed receipt predecessor alive through adoption or safely refuse Start when that predecessor is unavailable.

The first-copy probes used synthetic local files. The focused History and route suite passed 431 tests with three skipped, Studio Server built and typechecked, and the two original controls failed against 021580df.

— tai (automated review)

…by its read and keeps them

Every adopted copy follows the save receipts heard by the moment of its read, with or without a step, so a later
save writing the original back cannot move the start. A small file's read is reported before its close, which a slow
drive can hold. Bytes a save replaced in a file history has no copy of yet stay through pruning until it does.
@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

At 59ee3786, answering the three findings at 2e293fc3. Each case fails without its fix and passes now, and each fix was checked by breaking it.

  1. A late receipt with no step. Every adopted copy now follows only the receipts heard by the moment of its read, with or without a step. Case: filing of the first read (// before) is held. The file becomes // B, then Studio saves // before back with a receipt naming // B. The start is // before. Breaking it back to the live receipts turns this case red, along with the later-save case.
  2. A delayed close. A small file's read is reported once its bytes and stat are verified, before the handle's close is awaited. Close errors still propagate as before. Case: the first read's close is held until a step has written the file. The start is the original read before the step. Reporting after the close turns it red.
  3. Pruning the original a read-time receipt names. Bytes a save replaced in a file history has no copy of yet now stay through pruning until that file's copy is recorded. Case: Studio saves // B over // before before the stalled first read, and filing of // B is held. A later receipt starts a new chain, and a claim prunes at a 32-byte budget, which reaches the budget by pruning unreferenced bytes alone. The start is // before. Without the kept bytes, that prune removed the original and the start became // B.

Three test mocks of the blob store dropped put's read callback, and two of them also dropped the pin. They now pass the callback through. projectHistory.test.ts keeps its media cases unpinned, as they were. Passing the pin there changes their copy counts, and pinning has its own cases.

Checks

  • The step, first-copy and saving files passed 53 three times.
  • Whole studio-server suite: 2,312 passed, 0 failed, twice.
  • tsc clean.
  • The push gate ran the 4 named files 3 times, plus 23 covering files.

Not exercised: a native Windows run and a real drive that stops answering. These were Linux runs with local fixtures.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The three original first-copy cases pass at 59ee3786. Two budget regressions remain.

  1. P2 — Pending receipt bytes displace unrelated Undo entries (packages/studio-server/src/history/projectHistory.ts:1495–1510). Pruning keeps the receipt predecessor, but historyBytes still charges those temporary bytes to Undo. In a 128-byte budget probe, a held first copy retained its predecessor while two small index edits were folded out. The previous head kept both edits. Account for adoption's temporary retention the same way as other in-flight pins, so it does not consume Undo history.
  2. P2 — Ordinary new files can retain receipt blobs for the entire open session (projectHistory.ts:755). The map records every untracked file, including an ordinary file created and saved before a normal sweep. Its entries are only cleared on initial copy or adoption, which the new file never enters. After the new file was tracked and deleted, the original blob remained protected and a later unrelated Undo entry was folded. Reopening let the next prune reclaim it. Limit this retention to pending first copies and release it when there is no copy left to use it.

The focused History and route suites passed 434 cases with three skipped, and Studio Server built and typechecked. The original cases were also checked against the previous head. The probes used local test files.

— tai (automated review)

…t, not undo history

The bytes a save replaced are kept only for a file still owed its first copy, and they count as start rather than
undo history, so they never fold an unrelated edit out of the budget or stay for a file that never needed them.
@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

At 5a0b3a6c, answering both budget points at 59ee3786.

  1. Kept bytes displacing undo entries. The bytes kept for a pending first copy now count as start in historyBytes(), the same way pins do, so they never consume undo history. Case: a 100-byte original that an early save names waits for its file's held first copy while two small index edits are claimed under a 128-byte budget. Both edits stay. At 59ee3786 the first one was folded out, and counting the kept bytes as undo again turns the case red.
  2. A new file keeping bytes all session. Bytes are kept only for a file still owed its first copy (adopting), and they are dropped when its adoption records or ends. An ordinary new file never enters that list, so nothing is kept for it. There is no separate case for this: with point 1 fixed, its only remaining effect was bytes kept on disk until the next open, and I found no observable way to pin that. The earlier prune case still pins the kept bytes; its budget is now 16 bytes, since they no longer count. Removing the keep turns that case red again.

Checks

  • The step, first-copy and saving files passed 54 three times.
  • Whole studio-server suite: 2,313 passed, 0 failed. That run came before the prune case's budget changed to 16 bytes; the step file passed 29 three times after the change.
  • tsc clean.
  • The push gate ran the named files 3 times, plus covering files.

The same two fixes are in #8403, the split freeze fix.

Not exercised: a native Windows run and a real drive that stops answering. These were Linux runs with local fixtures.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two receipt-retention regressions are resolved. While the first copy is pending, its predecessor bytes survive pruning and the 128-byte test keeps both unrelated Undo entries. An ordinary new file no longer gets first-copy protection, and its obsolete receipt can be reclaimed in the same session.

I also checked repeated saves while publication was held. Both heads retained the same disconnected receipt blobs in that window. The previous head also discarded unrelated Undo entries. Once adoption finished, a subsequent prune reclaimed those blobs. A long-stalled publication can still hold receipt bytes until it finishes.

Studio Server built and typechecked. The focused History and route suites passed 435 tests with 3 skipped. Both targeted probes failed at the previous head and passed here. My local validation used Linux fixtures.

Required checks, including Windows render, passed. Other Windows test shards and several non-required checks were still running.

— tai (automated review)

@miguel-heygen
miguel-heygen added this pull request to the merge queue Nov 21, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 21, 2026
…line

# Conflicts:
#	packages/studio-server/src/history/firstCopy.test.ts
#	packages/studio-server/src/history/projectHistory.ts
#	scripts/package-size-budgets.json
@miguel-heygen

Copy link
Copy Markdown
Collaborator Author

At 46e78b12: merged main, which now carries #8403 (this PR's open-deadline half, split out and merged). No rebase; the reviewed commits are unchanged.

What the merge resolved:

Checks: the whole studio-server suite passed 2,317 with 0 failures, tsc is clean, and the push gate ran the named files 3 times plus 23 covering files.

@terencecho terencecho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The merge keeps both receipt cases from main and preserves the Undo and pruning safeguards from the reviewed branch. The timer guard prevents an already-owed read from starting another deadline when its slot opens.

All 19 tests in firstCopy.test.ts passed with one worker. Removing the guard made its regression test fail with one extra deadline. All required checks passed, including Windows render. Some non-required checks, including the other Windows test shards, were still running.

— tai (automated review)

@miguel-heygen
miguel-heygen added this pull request to the merge queue Nov 21, 2026
Merged via the queue into main with commit 267ffc4 Nov 21, 2026
83 checks passed
@miguel-heygen
miguel-heygen deleted the fix/history-copy-deadline branch November 21, 2026 23:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants